package me.wangcai.trafficpoliceai.tasks;

import lombok.SneakyThrows;
import org.bytedeco.javacpp.avcodec;
import org.bytedeco.javacpp.avformat;
import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacv.*;
import org.springframework.stereotype.Component;

public class VideoTask extends Thread {

    private String nowVideo = "404.mp4";
    public final String RTMPURL = "rtmp://localhost:1935/live/car";
    OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
    FFmpegFrameRecorder recorder;

    @SneakyThrows
    public VideoTask(){
        this.start();
    }

    public void recordPush(String video) throws Exception {
//        Loader.load(opencv_objdetect.class);
        FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault("E:/wangcai/a/video/" + video);
        grabber.start();
        long length = grabber.getLengthInTime();
        recorder = new FFmpegFrameRecorder(RTMPURL, 1280, 720);
        recorder.setVideoOption("crf", "28");
        recorder.setFrameRate(grabber.getVideoFrameRate());
        recorder.setVideoBitrate(2000000);
        recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264); // avcodec.AV_CODEC_ID_H264
        recorder.setFormat("flv");
        recorder.start();
//        recorder.setTimestamp(0);
        Frame grabFrame;
        opencv_core.IplImage grabbedImage;
        while ((grabFrame=grabber.grab()) != null && video.equals(nowVideo)) {
            grabbedImage = converter.convert(grabFrame);
            Frame rotatedFrame = converter.convert(grabbedImage);
            long time = System.currentTimeMillis() - length + grabFrame.timestamp;
//            recorder.setTimestamp(time);
            if(rotatedFrame!=null){
                recorder.record(rotatedFrame);
            }
            Thread.sleep(100 / (int)grabber.getVideoFrameRate());
        }
        if(nowVideo.equals(video)) nowVideo = "404.mp4";
        recorder.close();
        grabber.flush();
        grabber.stop();
    }

    public void setNowVideo(String nowVideo) {
        this.nowVideo = nowVideo;
    }

    @SneakyThrows
    @Override
    public void run() {
        while (true){
            try {
                recordPush(nowVideo);
            }catch (Exception err){
                err.printStackTrace();
            }

            Thread.sleep(1000);
        }
    }
}
